<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>用户管理</h1>
        <span class="user-count">共 {{ total }} 个用户</span>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyWord"
              placeholder="搜索用户姓名、账号或邮箱..."
              style="width: 300px;"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="部门">
            <el-tree-select
              v-model="searchForm.deptCode"
              :data="deptTreeOptions"
              :props="treeSelectProps"
              placeholder="选择部门"
              style="width: 200px;"
              clearable
              check-strictly
              :render-after-expand="false"
              :show-checkbox="false"
              :default-expand-all="false"
              :expand-on-click-node="false"
            />
          </el-form-item>
          
          <el-form-item label="角色">
            <el-select
              v-model="searchForm.role"
              placeholder="选择角色"
              style="width: 150px;"
              clearable
            >
              <el-option label="全部" :value="undefined" />
              <el-option label="管理员" :value="true" />
              <el-option label="普通用户" :value="false" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="users-card">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="users.length === 0" class="empty-state">
        <el-empty description="暂无用户">
          <el-button type="primary" @click="showCreateDialog = true">
            创建第一个用户
          </el-button>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table :data="users" stripe>
          <el-table-column prop="name" label="姓名" width="120">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="32">
                  {{ row.name?.charAt(0) || 'U' }}
                </el-avatar>
                <span class="user-name">{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="account" label="账号" width="150" />
          
          <el-table-column prop="email" label="邮箱" width="200" />
          
          <el-table-column prop="phone" label="手机号" width="130" />
          
          <el-table-column prop="sex" label="性别" width="80">
            <template #default="{ row }">
              <el-tag :type="row.sex === 0 ? 'primary' : 'success'" size="small">
                {{ row.sex === 0 ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="deptName" label="部门" width="120"></el-table-column>
          
          <el-table-column prop="isAdmin" label="角色" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isAdmin ? 'danger' : 'info'" size="small">
                {{ row.isAdmin ? '管理员' : '普通用户' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createdAt" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="editUser(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="text" size="small" @click="resetUserPassword(row)">
                <el-icon><Key /></el-icon>
                重置密码
              </el-button>
              <el-button 
                type="text" 
                size="small" 
                class="danger"
                @click="deleteUser(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            :current-page="pagination.pageNumber"
            :page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingUser ? '编辑用户' : '新增用户'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户账号" prop="account">
          <el-input 
            v-model="form.account" 
            placeholder="请输入用户账号"
            :disabled="editingUser"
          />
        </el-form-item>
        
        <el-form-item label="用户姓名" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入用户姓名"
            :disabled="editingUser"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item v-if="!editingUser" label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="部门" prop="deptCode">
          <el-tree-select
            v-model="form.deptCode"
            :data="deptTreeOptions"
            :props="treeSelectProps"
            placeholder="选择部门"
            clearable
            check-strictly
            :render-after-expand="false"
            :show-checkbox="false"
            :default-expand-all="true"
            :expand-on-click-node="false"
            style="width: 100%"
            class="dept-tree-select"
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="isAdmin">
          <el-radio-group v-model="form.isAdmin">
            <el-radio :label="false">普通用户</el-radio>
            <el-radio :label="true">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="showResetPasswordDialog"
      title="重置密码"
      width="400px"
      @close="resetPasswordForm"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showResetPasswordDialog = false">取消</el-button>
        <el-button type="primary" :loading="passwordSubmitting" @click="handleResetPassword">
          {{ passwordSubmitting ? '重置中...' : '重置' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, Edit, Key, Delete } from '@element-plus/icons-vue'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser as deleteUserApi,
  resetUserPassword as resetUserPasswordApi,
  type User, 
  type CreateUserRequest, 
  type UpdateUserRequest,
  type UserListParams,
  type ResetPasswordRequest
} from '@/api/user'
import { getDeptList, type Dept } from '@/api/dept'
import dayjs from 'dayjs'

const loading = ref(false)
const submitting = ref(false)
const passwordSubmitting = ref(false)
const showCreateDialog = ref(false)
const showResetPasswordDialog = ref(false)

const users = ref<User[]>([])
const departments = ref<Dept[]>([])

const editingUser = ref<User | null>(null)

// 树形选择器配置
const treeSelectProps = {
  children: 'children',
  label: 'deptName',
  value: 'deptCode'
}
const resettingUser = ref<User | null>(null)

const searchForm = reactive({
  keyWord: '',
  deptCode: '',
  role: undefined as boolean | undefined
})

const pagination = reactive({
  pageNumber: 1,
  pageSize: 20
})

const total = ref(0)

const formRef = ref<FormInstance>()
const form = reactive({
  account: '',
  name: '',
  email: '',
  phone: '',
  password: '',
  sex: 0,
  deptCode: '',
  isAdmin: false
})

const rules: FormRules = {
  account: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
    { max: 4, message: '姓名不能超过4个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  deptCode: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ]
}

const passwordFormRef = ref<FormInstance>()
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

const passwordRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (_, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const params: UserListParams = {
      keyWord: searchForm.keyWord || undefined,
      deptCode: searchForm.deptCode || undefined,
      pageDto: {
        pageNumber: pagination.pageNumber,
        pageSize: pagination.pageSize
      }
    }
    
    const result = await getUserList(params)
    users.value = result.data.items
    
    // 按角色筛选
    if (searchForm.role !== undefined) {
      users.value = users.value.filter(user => user.isAdmin === searchForm.role)
    }
    
    total.value = result.data.totalCount
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const fetchDepartments = async () => {
  try {
    const result = await getDeptList({
      pageDto: { pageNumber: 1, pageSize: 1000 }
    })
    departments.value = result.data.items
  } catch (error) {
    ElMessage.error('获取部门列表失败')
  }
}

// 构建部门树形结构
const buildDeptTree = (depts: Dept[]) => {
  const deptMap = new Map<number, any>()
  const rootDepts: any[] = []
  
  // 创建部门映射
  depts.forEach(dept => {
    deptMap.set(dept.id, {
      id: dept.id,
      deptName: dept.deptName,
      deptCode: dept.deptCode,
      parentDeptCode: dept.parentDeptCode,
      children: []
    })
  })
  
  // 构建树形结构
  depts.forEach(dept => {
    const deptNode = deptMap.get(dept.id)!
    if (dept.parentDeptCode) {
      const parent = Array.from(deptMap.values()).find(p => p.deptCode === dept.parentDeptCode)
      if (parent) {
        parent.children.push(deptNode)
      } else {
        rootDepts.push(deptNode)
      }
    } else {
      rootDepts.push(deptNode)
    }
  })
  
  return rootDepts
}

// 部门树形选项
const deptTreeOptions = computed(() => {
  return buildDeptTree(departments.value)
})

const handleSearch = () => {
  pagination.pageNumber = 1
  fetchUsers()
}

const handleReset = () => {
  searchForm.keyWord = ''
  searchForm.deptCode = ''
  searchForm.role = undefined
  pagination.pageNumber = 1
  fetchUsers()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNumber = 1
  fetchUsers()
}

const handleCurrentChange = (page: number) => {
  pagination.pageNumber = page
  fetchUsers()
}

const editUser = (user: User) => {
  editingUser.value = user
  form.account = user.account
  form.name = user.name
  form.email = user.email
  form.phone = user.phone
  form.sex = user.sex
  form.deptCode = user.deptCode
  form.isAdmin = user.isAdmin
  showCreateDialog.value = true
}

const resetUserPassword = (user: User) => {
  resettingUser.value = user
  showResetPasswordDialog.value = true
}

const deleteUser = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${user.name}" 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteUserApi(user.id)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetForm = () => {
  editingUser.value = null
  form.account = ''
  form.name = ''
  form.email = ''
  form.phone = ''
  form.password = ''
  form.sex = 0
  form.deptCode = ''
  form.isAdmin = false
  formRef.value?.resetFields()
}

const resetPasswordForm = () => {
  resettingUser.value = null
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    if (editingUser.value) {
      const updateData: UpdateUserRequest = {
        id: editingUser.value.id,
        account: form.account,
        email: form.email,
        phone: form.phone,
        sex: form.sex,
        deptCode: form.deptCode,
        isAdmin: form.isAdmin
      }
      await updateUser(updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateUserRequest = {
        account: form.account,
        name: form.name,
        email: form.email,
        phone: form.phone,
        password: form.password,
        sex: form.sex,
        deptCode: form.deptCode,
        isAdmin: form.isAdmin
      }
      await createUser(createData)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error(editingUser.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const handleResetPassword = async () => {
  if (!passwordFormRef.value || !resettingUser.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    passwordSubmitting.value = true
    if(resettingUser.value.id){
      const resetData: ResetPasswordRequest = {
        newPassword: passwordForm.newPassword,
        confirmPassword: passwordForm.confirmPassword,
        userId: resettingUser.value.id
      }
      await resetUserPasswordApi(resetData)
    }else{
      ElMessage.error('请选择用户')
      return
    }
    ElMessage.success('密码重置成功')
    showResetPasswordDialog.value = false
  } catch (error) {
    ElMessage.error('密码重置失败')
  } finally {
    passwordSubmitting.value = false
  }
}

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

onMounted(() => {
  fetchUsers()
  fetchDepartments()
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 24px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      h1 {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
      
      .user-count {
        color: #666;
        font-size: 14px;
        background: #f0f2f5;
        padding: 4px 12px;
        border-radius: 12px;
      }
    }
  }
  
  .search-card {
    margin-bottom: 24px;
    
    .search-form {
      .el-form {
        margin-bottom: 0;
      }
    }
  }
  
  .users-card {
    .loading-container {
      padding: 40px 0;
    }
    
    .empty-state {
      padding: 60px 0;
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .user-name {
        font-weight: 500;
      }
    }
    
    .danger {
      color: #f56c6c;
      
      &:hover {
        background-color: #fef0f0;
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

@media (max-width: 768px) {
  .user-management {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
      
      .header-right {
        width: 100%;
        
        .el-button {
          width: 100%;
        }
      }
    }
    
    .search-card {
      .search-form {
        .el-form {
          .el-form-item {
            margin-bottom: 12px;
          }
        }
      }
    }
    
    .users-card {
      .el-table {
        font-size: 12px;
      }
    }
  }
  
  .dept-tree-select {
    :deep(.el-tree-select__popper) {
      .el-tree {
        .el-tree-node {
          .el-tree-node__content {
            padding: 4px 8px;
            height: 32px;
            
            .el-tree-node__label {
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}
</style>
